<template>
  <div class="create-post-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="right" label-width="140px" class="account-form">
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="系统账号" prop="acctive">
            <el-input v-model="postForm.acctive" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="关联内部账号" prop="sub">
            <el-input v-model="postForm.sub" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="密码" prop="password">
            <el-input v-model="postForm.password" type="password" :disabled="isEdit" />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="postForm.confirmPassword" type="password" :disabled="isEdit" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="账号角色" prop="role">
            <el-select
              v-model="postForm.role"
              filterable
              style="width:100%"
            >
              <el-option
                v-for="item in roleOptions"
                :key="item.role"
                :label="item.rolename"
                :value="item.role"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt30">
        <el-col :span="18" :offset="3">
          <el-form-item>
            <el-button type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  getRolesList,
  getAccountInfo,
  addAccount,
  editAccount
} from '@/api/account'

const defaultForm = {
  id: undefined,
  acctive: '',
  sub: '',
  password: '',
  confirmPassword: '',
  role: ''
}

export default {
  name: 'AccountForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (this.postForm.acctive === '' && this.postForm.sub === '') {
        callback(new Error('请输入系统账号或关联内部账号'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (!this.isEdit && this.postForm.acctive !== '' && value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    const validateConfirmPass = (rule, value, callback) => {
      if (!this.isEdit && this.postForm.acctive !== '' && value === '') {
        callback(new Error('请再次输入密码'))
      } else if (!this.isEdit && this.postForm.acctive !== '' && value !== this.postForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    return {
      roleOptions: [],
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        acctive: [
          { validator: validateName, trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validateConfirmPass, trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择账号角色', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchRolesList()
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
  },
  methods: {
    fetchRolesList() {
      getRolesList().then(response => {
        // console.log(response)
        this.roleOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchData(id) {
      getAccountInfo(id).then(response => {
        const { data } = response
        // console.log(data)
        const { user } = data
        this.postForm.id = user.id
        this.postForm.acctive = user.acctive
        this.postForm.sub = user.sub
        this.postForm.password = user.password
        this.postForm.confirmPassword = user.password
        this.postForm.role = user.role
      }).catch(err => {
        console.log(err)
      })
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.isEdit) {
            editAccount(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          } else {
            addAccount(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.postForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.create-post-container {
  position: relative;
  .account-form {
    padding: 40px;
  }
}
</style>
